<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;
use Hash;

class UserController extends Controller
{

    public function postLogin(Request $request)
    {

        //验证用户名与密码信息
        $username = $request->username;
        $password = $request->password;


        //判断用户是否存在
        $res = DB::select('select * from users where username=?',[$username]);

        if(empty($res)){
            echo "<script>alert('抱歉，用户名不存在！');window.location.href='".$_SERVER['HTTP_REFERER']."';</script>";
        }
        if(Hash::check($password,$res[0]['password'])){

            $request->session()->put('userid',$res[0]['id']);
            $request->session()->put('username',$res[0]['username']);
            echo "<script>alert('恭喜，登陆成功！');window.location.href='".$_SERVER['HTTP_REFERER']."';</script>";
        }else{
            echo "<script>alert('密码错误！登录失败！');window.location.href='".$_SERVER['HTTP_REFERER']."';</script>";
        }
    }

    public function getLogout(Request $request)
    {
        $request->session()->forget('userid');
        $request->session()->forget('username');

        return redirect($_SERVER['HTTP_REFERER']);
    }
}
